import os,tempfile,shutil,commands
import pickle
import sys
import time
from crvclient import doSetUntilDone, doGetUntilDone

inf=open(sys.argv[1],"r")

vmid=pickle.load(inf)
serverstr=pickle.load(inf)
serverhostname=pickle.load(inf)

#Triggering policy:
#1. Triggered when new role is to be applied
#2. If one role failed the apply-run, (grep for "err:" in puppet output), trigger the application of the role it depends on (trigger provider).
#3. If one role succeeded in the apply-run, trigger all its non-local dependent (trigger receivers)

#Definition: Active Role = Role that has ProfileProvided=True

#Infinite loop which will take care of running puppet

#set last run to a very long time ago.
lastruntime=0

oufname="/var/log/crvclient.puppet.log"

while True:
    
    #check with server if need to run
#    cmdstr="curl -s \"%s/getVMAttr?vmid=%s&name=RunUpdate\""%(serverstr,vmid)
#    (status,output)=commands.getstatusoutput(cmdstr)
#    print "Running command=%s, status=%d, output=%s"%(cmdstr,status,output)
#    if status==0 and output=="True":
#        RunUpdate=True
#    else:
#        RunUpdate=False

    output=doGetUntilDone("%s/getVMAttr?vmid=%s&name=RunUpdate"%(serverstr,vmid))
    if output=="None":
        RunUpdate=999999999
    else:
        RunUpdate=int(output)

    print "RunUpdate=%s"%(str(RunUpdate))

    currenttime=time.time()
    
    #if need to run
    if (currenttime-lastruntime)>RunUpdate:
    
        #    run puppet once
        ouf=open(oufname,"a")
        starttime=time.time()
        cmdstr='puppetd --test --debug --server=%s' % serverhostname
        (status,output)=commands.getstatusoutput(cmdstr)
        endtime=time.time()
        ouf.write("Command=%s, status=%d, output=%s\n"%(cmdstr,status,output))
        ouf.write("Start time=%f, end time=%f\n"%(starttime,endtime))
        ouf.close()

        lastruntime=currenttime

        puppetsuccess=True
        if output.find("err:")>=0:
            puppetsuccess=False

        #set all active role to ProfileApplied=True
        if puppetsuccess:
            doSetUntilDone("%s/setVMActiveRoleSuccess?vmid=%s"%(serverstr,vmid))

        else:
            #do nothing and wait for next update and hope errors are fixed
            pass
        
    time.sleep(10)
    
